package com.xzp.yygh.msm.controller;



import com.xzp.yygh.common.result.Result;
import com.xzp.yygh.msm.service.MsmService;
import com.xzp.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成验证码, 利用阿里云发送短信，并将{phone: code}存入redis
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        // 从redis中取
        String code = redisTemplate.opsForValue().get(phone);
        // code存在于redis, 说明之前发过短信，这回就不发了
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        // 生成验证码
        code = RandomUtil.getSixBitRandom();
        System.out.println(code);
        // 调用service方法，通过阿里云发送短信
//        boolean isSend = msmService.send(phone, code);
        boolean isSend = true;
        if(isSend){
            // 将key:phone与value:code存入redis, 2为度量单位， TimeUnit.MINUTES表示单位是分。
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.fail().message("发送短信失败");
        }
    }

}
